package org.jetlinks.pro.clickhouse.metadata;

import org.hswebframework.ezorm.rdb.executor.DefaultBatchSqlRequest;
import org.hswebframework.ezorm.rdb.metadata.RDBColumnMetadata;
import org.hswebframework.ezorm.rdb.metadata.dialect.DataTypeBuilder;
import org.hswebframework.ezorm.rdb.operator.builder.fragments.PrepareSqlFragments;
import org.hswebframework.ezorm.rdb.operator.builder.fragments.ddl.CommonAlterTableSqlBuilder;
import org.jetlinks.pro.clickhouse.engine.Engine;

import static org.hswebframework.ezorm.rdb.operator.builder.fragments.PrepareSqlFragments.of;

public class ClickHouseAlterTableSqlBuilder extends CommonAlterTableSqlBuilder {

    @Override
    protected void appendAddColumnCommentSql(DefaultBatchSqlRequest batch, RDBColumnMetadata column) {

    }

    protected PrepareSqlFragments createAlterTable(RDBColumnMetadata column) {
        Engine engine = column.findFeatureNow(Engine.ID);
        PrepareSqlFragments fragments = of()
            .addSql("ALTER", "TABLE", column.getOwner().getFullName());
        if (engine.isDistributed()) {
            fragments.addSql("ON CLUSTER", engine.getCluster());
        }
        return fragments;
    }

    @Override
    protected void appendAddColumnSql(DefaultBatchSqlRequest batch, RDBColumnMetadata column) {
        DataTypeBuilder type = ((DataTypeBuilder) column.getType());
        PrepareSqlFragments fragments = createAlterTable(column);
        fragments.addSql("ADD COLUMN IF NOT EXISTS")
                 .addSql(column.getName())
                 .addSql(type.createColumnDataType(column));

        batch.addBatch(fragments.toRequest());
    }

    @Override
    protected void appendDropColumnSql(DefaultBatchSqlRequest batch, RDBColumnMetadata drop) {
        PrepareSqlFragments fragments = createAlterTable(drop);
        fragments.addSql("DROP COLUMN IF EXISTS")
                 .addSql(drop.getName());

        batch.addBatch(fragments.toRequest());
    }

    @Override
    protected void appendAlterColumnSql(DefaultBatchSqlRequest batch,
                                        RDBColumnMetadata oldColumn,
                                        RDBColumnMetadata newColumn) {
        DataTypeBuilder type = ((DataTypeBuilder) newColumn.getType());
        PrepareSqlFragments fragments = createAlterTable(newColumn);
        fragments.addSql("MODIFY COLUMN IF EXISTS")
                 .addSql(newColumn.getName())
                 .addSql(type.createColumnDataType(newColumn));

        batch.addBatch(fragments.toRequest());
    }
}
